package com.hmall.gateway.filters;

import cn.hutool.core.collection.CollectionUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.根据请求路径判断是否需要进行拦截
        if(isExcludes(request.getPath().toString())){
            //放行
           return chain.filter(exchange);
        }
        //3.拦截
        List<String> tokens = request.getHeaders().get("authorization");
        ServerHttpResponse response = exchange.getResponse();
        if(!CollectionUtil.isEmpty(tokens)){
            //3.1取出token,并解析
            String token = tokens.get(0);
            log.info(token);
            Long userId=null;
            try {
                userId = jwtTool.parseToken(token);
            } catch (Exception e) {
                //解析失败,返回响应状态码
                log.info("token解析失败,返回错误信息");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //3.2将解析出的信息保存到请求头
            String userInfo=userId.toString();
            ServerWebExchange exchange1 = exchange.mutate()
                    .request(builder -> builder.header("userId", userInfo))
                    .build();
            //4.放行
            return chain.filter(exchange1);
        }
        log.info("header不存在token");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    private boolean isExcludes(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
